import React, { useState, useEffect } from 'react'
import './index.scss'
import NumberPad from '../../components/customCopm/NumberPad'
import IconSelection from '../../components/customCopm/IconSelection'
import { View, Image } from '@tarojs/components'
import { Tabs, Input } from '@nutui/nutui-react-taro'
import { getCurrentDateTime } from '../../utility'
import Taro, { useDidShow } from '@tarojs/taro'

// 定义账单数据类型
interface BillRecord {
  amount: string           // 输入金额
  type: string | number    // 收入(0)或支出(1)
  selectedType: string     // 选中的图标名称
  remarks: string          // 备注
  date: string            // 时间
  selectedIcon: string       //图表路径
  id: string              // 唯一标识
}
const Index = () => {
  // tab金额
  const [amount, setAmount] = useState("0");
  // 图标显示
  const [selectedIcon, setSelectedIcon] = useState("../../resource/other.svg");
  const [selectedType, setSelectedType] = useState("other");
  const [remarks, setRemarks] = useState("");
  // tab栏
  const [tab1value, setTab1value] = useState<string | number>('0')
  // 控制 NumberPad 显示隐藏
  const [showNumberPad, setShowNumberPad] = useState(true)
  // 账单记录列表
  const [billRecords, setBillRecords] = useState<BillRecord[]>([])

  // 本月预算（字符串以便输入控件受控）
  const [monthBudget, setMonthBudget] = useState<string>('')

  // 主题：light | dark
  const [theme, setTheme] = useState<'light' | 'dark'>(() => {
    try {
      const cached = Taro.getStorageSync('app_theme') as 'light' | 'dark'
      return cached === 'dark' ? 'dark' : 'light'
    } catch {
      return 'light'
    }
  })

  // 本地存储的 key
  const STORAGE_KEY = 'bill_records'
  const getMonthKey = () => {
    const now = new Date()
    return `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}`
  }
  const BUDGET_STORAGE_KEY = (month: string) => `budget_${month}`

  // 组件加载时从本地存储读取数据
  useEffect(() => {
    loadBillRecords()
    loadMonthBudget()
  }, [])

  // 页面显示时同步主题（从其他页面切换后能及时生效）
  useDidShow(() => {
    try {
      const cached = Taro.getStorageSync('app_theme') as 'light' | 'dark'
      setTheme(cached === 'dark' ? 'dark' : 'light')
    } catch {}
  })

  // 从本地存储加载账单记录
  const loadBillRecords = async () => {
    try {
      const data = await Taro.getStorage({ key: STORAGE_KEY })
      if (data.data) {
        setBillRecords(JSON.parse(data.data))
        console.log('加载账单记录:', JSON.parse(data.data))
      }
    } catch (error) {
      console.log('暂无账单记录')
      setBillRecords([])
    }
  }

  // 加载当月预算
  const loadMonthBudget = async () => {
    try {
      const key = BUDGET_STORAGE_KEY(getMonthKey())
      const data = await Taro.getStorage({ key })
      if (data?.data !== undefined && data?.data !== null) {
        setMonthBudget(String(data.data))
      } else {
        setMonthBudget('')
      }
    } catch {
      setMonthBudget('')
    }
  }

  // 保存当月预算
  const saveMonthBudget = async (value: string) => {
    const key = BUDGET_STORAGE_KEY(getMonthKey())
    try {
      await Taro.setStorage({ key, data: value })
      Taro.showToast({ title: '已保存当月预算', icon: 'success', duration: 1000 })
    } catch (e) {
      Taro.showToast({ title: '保存失败', icon: 'none' })
    }
  }

  // 计算当月总支出
  const calculateMonthExpense = (): number => {
    const now = new Date()
    const m = now.getMonth()
    const y = now.getFullYear()
    let total = 0
    billRecords.forEach(r => {
      const d = new Date(r.date)
      if (d.getFullYear() === y && d.getMonth() === m && String(r.type) === '1') {
        const amt = parseFloat(r.amount)
        if (!Number.isNaN(amt)) total += amt
      }
    })
    return total
  }

  // 保存账单记录到本地存储
  const saveBillRecord = async (record: BillRecord) => {
    try {
      const newRecords = [...billRecords, record]
      await Taro.setStorage({
        key: STORAGE_KEY,
        data: JSON.stringify(newRecords)
      })
      setBillRecords(newRecords)
      console.log('保存成功:', record)
      console.log('当前所有记录:', newRecords)
      
      Taro.showToast({
        title: '记账成功',
        icon: 'success',
        duration: 1500
      })
    } catch (error) {
      console.error('保存失败:', error)
      Taro.showToast({
        title: '保存失败',
        icon: 'error',
        duration: 1500
      })
    }
  }
  function handleNumberInput(value: string): void {
    console.log(value, ' 点击按钮');

    if (value === 'backspace') {
      // 删除最后一位
      if (amount.length > 1) {
        setAmount(amount.slice(0, -1));
      } else {
        setAmount("0");
      }
    } else if (value === "clear") {
      // 清零
      setAmount("0");
    } else if (value === "ok") {
      // 确认按钮
      console.log(amount, ' 确认按钮');
      
      // 验证金额
      if (amount === '' || amount === '0') {
        Taro.showToast({
          title: '请输入金额',
          icon: 'none',
          duration: 1500
        })
        return
      }

      // 创建账单记录
      const billRecord: BillRecord = {
        amount: amount,
        type: tab1value,
        selectedIcon:selectedIcon,
        selectedType: selectedType,
        remarks: remarks,
        date: getCurrentDateTime(),
        id: Date.now().toString() + Math.random().toString(36).substr(2, 9)
      }

      // 保存到本地存储
      saveBillRecord(billRecord)

      // 重置表单
      setAmount("0");
      setRemarks("");
      setSelectedIcon("../../resource/other.svg");
      setSelectedType("other");
    } else if (value === ".") {
      // 添加小数点
      if (!amount.includes(".")) {
        setAmount(amount === "0" ? "0." : amount + ".");
      }
    } else {
      // 数字输入
      setAmount(amount === "0" ? value : amount + value);
    }
  }

  return (
      <View className={`index-page ${theme === 'dark' ? 'theme-dark' : 'theme-light'}`}>
        <Tabs
          value={tab1value}
          onChange={(value) => {
            setTab1value(value)
          }}
          activeType="card"
        >
          <Tabs.TabPane title="收入" value="0">

          </Tabs.TabPane>
          <Tabs.TabPane title="支出" value="1">

          </Tabs.TabPane>
        </Tabs>


        <View className="indexPageAmount">
          <Image
            src={selectedIcon}
            className="selectionicon"
            mode="aspectFit"
          />

          <View className=''>
            <View className="" style={{ marginLeft: '20px' }}>¥{amount}</View>
          </View>
        </View>

        <View className="flex" style={{ display: 'flex' }}>

          {/* 图标选择组件示例 */}
          <View className="icon-selection-demo">

            <IconSelection
              selectedIcon={selectedIcon}
              onSelect={(iconName, itemIcon) => {
                console.log('选中图标:', iconName)
                setSelectedIcon(itemIcon)
                setSelectedType(iconName)
              }}
            />
          </View>
        </View>

        <View className="" style={{ display: 'flex', justifyContent: 'space-between', alignContent: 'center', backgroundColor: '#fff', padding: '10px' }}>

          <View style={{ marginTop: '5px' }}>
            备注：
          </View>

          <Input
            placeholder="请输入文本"
            style={{ fontSize: '20px' }}
            onFocus={() => {
              setShowNumberPad(false)
            }}
            onBlur={() => {
              setShowNumberPad(true)
            }}
            onChange={(v) => {
              setRemarks(v)
            }} />

        </View>

        {/* 月度预算 */}
        <View className="budget-card">
          <View className="budget-row">
            <View className="budget-label">本月预算</View>
            <Input
              placeholder="输入金额"
              type="digit"
              value={monthBudget}
              onFocus={() => {
                setShowNumberPad(false)
              }}
              onBlur={() => {
                saveMonthBudget(monthBudget || '0')
                setShowNumberPad(true)
              }}
              style={{ fontSize: '18px', textAlign: 'right' }}
              onChange={(v) => {
                // 仅保留数字与小数点
                const next = String(v).replace(/[^0-9.]/g, '')

                setMonthBudget(next)
              }}
            
            />
          </View>

          {(() => {
            const budgetNum = parseFloat(monthBudget || '0') || 0
            const spent = calculateMonthExpense()
            const remain = budgetNum - spent
            const negative = remain < 0
            return (
              <View className="budget-stats">
                <View className="budget-stat">
                  <View className="stat-label">已用</View>
                  <View className="stat-value expense">¥{spent.toFixed(2)}</View>
                </View>
                <View className="budget-stat">
                  <View className="stat-label">剩余</View>
                  <View className={`stat-value ${negative ? 'expense' : 'income'}`}>¥{remain.toFixed(2)}</View>
                </View>
              </View>
            )
          })()}
        </View>

        {showNumberPad && (
          <View className="number-pad-wrapper">
            <NumberPad onInput={handleNumberInput} />
          </View>
        )}
      </View>
  )
}

export default Index